//
//  AnimController.cpp
//  HelloWorld
//
//  Created by Marius Ibanez on 27/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include <iostream>
#include "AnimController.h"

#include "InputsManager.h"
#include "CharacterController.h"

b2Body* AnimController::getBody() 
{ 
    return mController->getBody(); 
}

AnimController::AnimController(BasicCharacterController* controller)
{
    mController = controller; 
    mImg = NULL;
	anim_act = -1;
}

void AnimController::PlayAnim(int ANIM_ID)
{
    if( ANIM_ID == anim_act )
		return;
    
	if( anim_act != -1)
		mImg->stopAction( mAnimList[ anim_act ] );
    
	mImg->runAction( mAnimList[ ANIM_ID ] );
    
	anim_act = ANIM_ID;
}


BasicAnimController::BasicAnimController(BasicCharacterController* controller):
    AnimController(controller)
{
    for(int i=0; i<BASIC_ANIM_COUNT; i++)
    {
        mAnimList.push_back(NULL);
    }
}
void BasicAnimController::update( ccTime dt)
{
    mImg->setPosition( CCPointMake( getBody()->GetPosition().x * PTM_RATIO, getBody()->GetPosition().y * PTM_RATIO) );
    mImg->setRotation( -1 * CC_RADIANS_TO_DEGREES(getBody()->GetAngle()) );
    
    float xVel = abs( getBody()->GetLinearVelocity().x );
	float xRealVel =  getBody()->GetLinearVelocity().x ;
	float yVel =  getBody()->GetLinearVelocity().y;
	
	if( mController->IsTouchingWall() )
	{
		if( mController->IsTouchingGround() )
			PlayAnim( ANIM_IDLE );
		else
			PlayAnim( ANIM_BREAK );
	}
	else if( yVel > 0.1f  && mController->IsTouchingGround() == false )
	{
		if( anim_act != ANIM_JUMP &&  anim_act != ANIM_SPRINT_JUMP )
		{
			if( xVel > 8.0f )
				PlayAnim( ANIM_SPRINT_JUMP );
			else
				PlayAnim( ANIM_JUMP );
		}
	}
	else if(  yVel < -0.1f && mController->IsTouchingGround() == false )
	{
		if( anim_act != ANIM_SPRINT_JUMP )
			PlayAnim( ANIM_AIR_DOWN );
	}
	else if( xVel == 0.0f && mController->IsTouchingGround() )
	{
		PlayAnim( ANIM_IDLE );
	} 
	else if( INPUTS->GetKeyState( KEY_ID::KEY_LEFT ).Press && xRealVel > 0.0f && mController->IsTouchingGround() )
	{
		PlayAnim( ANIM_BREAK );
	}
	else if( INPUTS->GetKeyState( KEY_ID::KEY_RIGHT ).Press && xRealVel < 0.0f && mController->IsTouchingGround() )
	{
		PlayAnim( ANIM_BREAK );
	}
	else if( xVel < 8.0f && mController->IsTouchingGround() )
	{
		PlayAnim( ANIM_WALK );
	}
	else if( mController->IsTouchingGround() )
	{
		PlayAnim( ANIM_SPRINT );
	}
    
	if(  getBody()->GetLinearVelocity().x > 0.0f )
	{
		mImg->setFlipX( false );
	}
	else
	{
		mImg->setFlipX( true );
	}
}